package com.good.child.ui.activity.camera

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.Utils
import com.good.child.BuildConfig
import com.good.child.R
import java.io.File
import java.io.FileNotFoundException

/**
 * 作者：suichengju
 * 时间：2024/7/22:20:09
 * 邮箱：325927775@qq.com
 * 说明：
 */
object FileHelper {
    fun saveImageToGallery(context: Context, file: File, fileName: String) {
        try {
            MediaStore.Images.Media.insertImage(context.contentResolver, file.absolutePath, fileName, null)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, getUriFromFile(context, file)))
    }

    fun saveVideoToGallery(context: Context, file: File, fileName: String) {
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, getUriFromFile(context, file)))
    }

    fun getSavedFile(appendix: String): File {
        val appDir = File(getExternalPicturesPath(), Utils.getApp().getString(R.string.app_name))
        FileUtils.createOrExistsDir(appDir.path)
        val fileName = "${System.currentTimeMillis()}.${appendix}"
        return File(appDir, fileName)
    }

    /**
     * Return the path of /storage/emulated/0/Pictures.
     *
     * @return the path of /storage/emulated/0/Pictures
     */
    fun getExternalPicturesPath(): String? {
        return if (isExternalStorageDisable()) "" else Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES
        ).absolutePath
    }

    /*------------------------------------ inner methods ----------------------------------------*/
    private fun isExternalStorageDisable(): Boolean {
        return Environment.MEDIA_MOUNTED != Environment.getExternalStorageState()
    }

    fun getUriFromFile(context: Context, file: File): Uri {
        return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
        } else {
            Uri.fromFile(file)
        }
    }
}
